package org.example.rubbish.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.example.rubbish.entity.Site;
import org.example.rubbish.mapper.SiteMapper;
import org.example.rubbish.service.SiteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class SiteServiceImpl implements SiteService {

    @Autowired
    private SiteMapper siteMapper;

    @Override
    public Site getSiteById(Long id) {
        try {
            return siteMapper.selectById(id);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public Site getSiteByStationName(String stationName) {
        try {
            return siteMapper.selectByStationName(stationName);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public List<Site> getAllActiveSites() {
        try {
            return siteMapper.selectAllActiveSites();
        } catch (Exception e) {
            return List.of();
        }
    }

    @Override
    public boolean validateTerminalId(String terminalId) {
        try {
            // 终端ID应该是sites表的ID
            Long siteId = Long.parseLong(terminalId);
            Boolean exists = siteMapper.existsByIdAndActive(siteId);
            return exists != null && exists;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    @Override
    public String getStationNameByTerminalId(String terminalId) {
        try {
            Long siteId = Long.parseLong(terminalId);
            Site site = siteMapper.selectById(siteId);
            return site != null ? site.getStationName() : "未知站点";
        } catch (Exception e) {
            return "无效终端";
        }
    }

    @Override
    public Site getSiteByTerminalId(String terminalId) {
        try {
            Long siteId = Long.parseLong(terminalId);
            return siteMapper.selectById(siteId);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public String getStationCodeByTerminalId(String terminalId) {
        try {
            Long siteId = Long.parseLong(terminalId);
            Site site = siteMapper.selectById(siteId);
            return site != null ? site.getStationCode() : "UNKNOWN";
        } catch (Exception e) {
            return "UNKNOWN";
        }
    }
}